package com.dx.mes.service.brm.service;

import com.dx.common.table.ppt.*;
import com.dx.mes.common.dao.*;
import com.dx.mes.common.transcoder.util.*;
import com.dx.mes.facade.brm.service.IFbpbistoolService;
import com.dx.mes.facade.brm.tx.Fbpbistol.*;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.sql.Timestamp;
import java.util.*;

import static com.dx.mes.common.bean.def.GenericDef.*;


@Service("fbpbistoolService")
@SuppressWarnings({"unchecked"})
public class FbpbistoolService implements IFbpbistoolService {
	private static final String TX_NAME = "FBPBISTOL";
	private LogUtils logUtils;
	
	@Autowired
	private IBisToolDao bisToolDao;

	@Autowired
	private IRetToolPtDao retToolPtDao;
	
	@Autowired
	private IRetToolStDao retToolStDao;

	@Autowired
	private IBisToolGrDao bisToolGrDao;

	@Autowired
	private IBisOpeDao   bisOpeDao;
	@Autowired
	private IRetToolPmDao   retToolPmDao;



	public String subMainProc(String evt_no,String strInMsg) {
		AppContext.clear();
		AppContext.setCurrServiceName(FbpbistoolService.class.getSimpleName());
		AppContext.setCurrEventNumber(evt_no);
		logUtils = new LogUtils(FbpbistoolService.class);
		logUtils.info("[InTrx:" + strInMsg + "]");
		
		String outMsg = "";
		FbpbistolO outTrx = new FbpbistolO();

		outTrx.setTrx_id(TX_NAME);
		outTrx.setType_id(TRX_OUT);
		outTrx.setRtn_code(String.valueOf(RETURN_CODE_SET_ERROR));
		
		try {
			FbpbistolI inTrx = JacksonUtil.fromJson(strInMsg, FbpbistolI.class);
			char action_flg = inTrx.getAction_flg().charAt(0);
			switch (action_flg) {
			case ACTION_FLG_QUERY:
				queryByCondition(inTrx,outTrx);
				break;
			case ACTION_FLG_INQUIRE:
				queryByToolId(inTrx,outTrx); //查询设备信息带设备状态
				break;
			case 'Y':
				queryTools(inTrx); //查询所有设备状态信息
				break;
			case ACTION_FLG_ADD:
				addFnc(inTrx,outTrx);
				break;
			case ACTION_FLG_UPDATE:
				updateFnc(inTrx,outTrx);
				break;
			case ACTION_FLG_DELETE:
				deleteFnc(inTrx,outTrx);
				break;
			case ACTION_FLG_LIST_WHOLE:
				listAllFnc(outTrx);
				break;
			case ACTION_FLG_QUERY_BY_RUN_MODE:
				listByRunMode(inTrx,outTrx);
				break;
			case 'T':
				getRootTool(inTrx,outTrx);
				break;
			case 'S':
				getRootToolByToolId(inTrx,outTrx);
				break;
			case 'M':
				queryToolByFacyory(inTrx,outTrx);
				break;
			case 'N':
				getToolByProc(inTrx,outTrx);
				break;
			case 'O':
				querytoolStatus(inTrx,outTrx);//获得上下保养时间
				break;
			default:
				errActionFnc(outTrx);
			}
			if (RETURN_CODE_OK.equals(outTrx.getRtn_code())) {
				bisToolDao.flushCurSession();
			} else {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}

		} catch (Exception ex) {
			outTrx.setRtn_code(RETURN_CODE_UNKNOWN);
			outTrx.setRtn_mesg(ex.toString());
			ex.printStackTrace();
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		} finally {
			outMsg = JacksonUtil.toJSONStr(outTrx);
			logUtils.info("[OutTrx:" + outMsg + "]");
		}
		return outMsg;
	}

	private void listByRunMode(FbpbistolI inTrx, FbpbistolO outTrx) {
		List<FbpbistolOA> oaryAList = new ArrayList<FbpbistolOA>();
		List<FbpbistolOB> oaryBList = new ArrayList<FbpbistolOB>();
		
		FbpbistolIA iary = inTrx.getIary().get(0);
		String tool_run_mode = iary.getTool_run_mode();
		String unit_typ = iary.getUnit_typ();
		String hql = "FROM Ret_tool_st where 1=1 ";
		
		if (!Util.isSpaceCheck(tool_run_mode)) {
			hql = hql + " and tool_run_mode in('" + tool_run_mode + "')";
		}
		List<Ret_tool_st> bisToolstList = retToolStDao.find(hql);
		Bis_tool bis_tool2 ;
		List<Bis_tool> bisToolList2 = new ArrayList<Bis_tool>();
		if(bisToolstList.size()>0){
			for(Ret_tool_st tool_st : bisToolstList){
				FbpbistolOB oaryB = new FbpbistolOB();
				oaryB.setTool_id(tool_st.getTool_id_fk());
				bis_tool2 = bisToolDao.get(tool_st.getTool_id_fk());
				bisToolList2.add(bis_tool2);
				oaryBList.add(oaryB);
			}
			
		}
		String root_tool_id = iary.getRoot_tool_id();
		String  hql2 = "FROM Bis_tool where 1=1 ";
		if(!Util.isSpaceCheck(unit_typ)){
			hql2 = hql2 + " and unit_typ ='" + unit_typ + "'";
		}
		if (!Util.isSpaceCheck(root_tool_id)) {
			hql2 = hql2 + " and root_tool_id = '"+root_tool_id+"'";
		}
		List<Bis_tool> bisToolList = bisToolDao.find(hql2);
		List<Bis_tool> bisToolList3 = new ArrayList<Bis_tool>();
		if(bisToolList.size()>0){
			for (Bis_tool bis_tool : bisToolList) {
				if (bisToolList2.contains(bis_tool)) {
					bisToolList3.add(bis_tool);
				}
			}
		}
		if (bisToolList3.size() >0) {
			for (Bis_tool bis_tool : bisToolList3) {
				FbpbistolOA oaryA = new FbpbistolOA();
				oaryA.setTool_id(bis_tool.getTool_id());
				if (bis_tool != null) {
					oaryA.setTool_id(bis_tool.getTool_id());
					oaryA.setTool_dsc(bis_tool.getTool_dsc());
					oaryAList.add(oaryA);
				}
			}
		}
		
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
		outTrx.setOary(oaryAList);
		outTrx.setOaryB(oaryBList);
		outTrx.setTbl_cnt_B(oaryBList.size());
		outTrx.setTbl_cnt(oaryAList.size());
	}

	private void queryByToolId(FbpbistolI inTrx, FbpbistolO outTrx) {
		// TODO Auto-generated method stub
		FbpbistolIA iary = inTrx.getIary().get(0);
		Bis_tool bis_tool = bisToolDao.get(iary.getTool_id());
		List<FbpbistolOA> oaryList = new ArrayList<FbpbistolOA>();
		List<FbpbistolOB> oaryBList = new ArrayList<FbpbistolOB>();
		
		FbpbistolOA oary = new FbpbistolOA();
		oary.setTool_id(bis_tool.getTool_id());
		oary.setTool_dsc(bis_tool.getTool_dsc());
		oary.setUnit_typ(bis_tool.getUnit_typ());
		oary.setRoot_tool_id(bis_tool.getRoot_tool_id());
		oary.setTool_cate(bis_tool.getTool_cate());
		oary.setBay_id(bis_tool.getBay_id());
		oary.setFloor_code(bis_tool.getFloor_code());
		oary.setTool_trns_cate(bis_tool.getTool_trns_cate());
		oary.setTool_ip(bis_tool.getTool_ip());
		oary.setFab_id_fk(bis_tool.getFab_id_fk());
		oary.setTool_code(bis_tool.getTool_code());
		oary.setFab_site_fk(bis_tool.getFab_site_fk());
		Ret_tool_st ret_tool_st = retToolStDao.get(iary.getTool_id());
		if(ret_tool_st!=null){
			oary.setTool_run_mode(ret_tool_st.getTool_run_mode());
			oary.setTool_ctrl_mode(ret_tool_st.getTool_ctrl_mode());
			oary.setTool_stat(ret_tool_st.getTool_stat());
			oary.setTool_sub_stat(ret_tool_st.getTool_sub_stat());
			oary.setPv_tool_sub_stat(ret_tool_st.getPv_tool_sub_stat());
			if (null != ret_tool_st.getEvt_timestamp()) {
				oary.setEvt_timestamp(ret_tool_st.getEvt_timestamp().toString());
			}
			oary.setEvt_usr(ret_tool_st.getEvt_usr());
			oary.setTool_lock_flg(ret_tool_st.getTool_lock_flg());
			oary.setTool_hold_flg(ret_tool_st.getTool_hold_flg());
			Timestamp evt_timestamp = Util.getCurrentTimestamp();

			if(null !=ret_tool_st.getLd_last_fetch_timestamp()){
				oary.setLd_last_fetch_timestamp(ret_tool_st.getLd_last_fetch_timestamp().toString());
				long time_differ = Util.getDiffMin(ret_tool_st.getLd_last_fetch_timestamp(), evt_timestamp);
				oary.setLd_time_differ(String.valueOf(time_differ));
			}
			if(null != ret_tool_st.getUl_last_fetch_timestamp()){
				oary.setUl_last_fetch_timestamp(ret_tool_st.getUl_last_fetch_timestamp().toString());
				long time_differ = Util.getDiffMin(ret_tool_st.getUl_last_fetch_timestamp(), evt_timestamp);
				oary.setUl_time_differ(String.valueOf(time_differ));
			}
		}
		String hqls = "FROM Bis_tool_gr where 1=1 ";
		if (iary.getTool_id() != null) {
			hqls = hqls + " and tool_id_fk='" + iary.getTool_id() + "'";
		}
		List<Bis_tool_gr> bisToolGr = bisToolGrDao.find(hqls);
		if(bisToolGr.size()>0){
			oary.setTool_group_id_fk(bisToolGr.get(0).getId().getToolg_id());
		}
		oaryList.add(oary);
		
		
		String hql = "FROM Ret_tool_pt where 1=1 ";
		if (iary.getTool_id() != null) {
			hql = hql + " and tool_id_fk='" + iary.getTool_id() + "'";
		}
		if (iary.getPort_typ() != null) {
			hql = hql + " and port_typ = '"+ iary.getPort_typ() + "'";
		}
		List<Ret_tool_pt> bisToolPtList = retToolPtDao.find(hql);
		for(Ret_tool_pt tool_pt : bisToolPtList){
			FbpbistolOB oaryB = new FbpbistolOB();
			oaryB.setTool_id(tool_pt.getId().getTool_id_fk());
			oaryB.setPort_id(tool_pt.getId().getPort_id());
			oaryB.setPort_typ(tool_pt.getPort_typ());
			oaryB.setPort_stat(tool_pt.getPort_stat());
			oaryB.setPort_ng_flg(tool_pt.getPort_ng_flg());
			oaryB.setFrom_stk_id(tool_pt.getFrom_stk_id());
			oaryB.setTo_stk_id(tool_pt.getTo_stk_id());
			oaryB.setPort_active_flg(tool_pt.getPort_active_flg());
			oaryB.setLst_xfr_timestamp(tool_pt.getLst_xfr_timestamp());
			oaryB.setPort_timestamp(tool_pt.getPort_timestamp());
			oaryB.setRtd_flg(tool_pt.getRtd_flg());
			oaryB.setXfr_id(tool_pt.getXfr_id());
			oaryB.setXfr_node(tool_pt.getXfr_node());
			oaryBList.add(oaryB);
		}
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
		outTrx.setOary(oaryList);
		outTrx.setOaryB(oaryBList);
		outTrx.setTbl_cnt(oaryList.size());
		outTrx.setTbl_cnt_B(oaryBList.size());
	}


	//查询产线的设备状态
	public FbpbistolO queryTools (FbpbistolI inTrx) {
		FbpbistolO outTrx = new FbpbistolO();
		List<FbpbistolOA> oaryList = new ArrayList<>();
		String sql_tools = "select A.TOOL_ID, A.TOOL_DSC, B.TOOL_STAT from " +
				"bis_tool A, ret_tool_st B where A.TOOL_ID = B.TOOL_ID_FK and A.UNIT_TYP='MAIN'";
		if (!Util.isSpaceCheck(inTrx.getIary().get(0).getFab_id_fk())) {
			sql_tools += "and A.FAB_ID_FK = '"+inTrx.getIary().get(0).getFab_id_fk() + "'";
		}
		List<Object[]> objList = bisToolDao.findBySQL(sql_tools);
		if (objList.size() > 0) {
			for (int i=0; i<objList.size(); i++) {
				Object[] obj = objList.get(i);
				FbpbistolOA fbpbistolOA = new FbpbistolOA();
				fbpbistolOA.setTool_id(obj[0].toString());
				fbpbistolOA.setTool_dsc(obj[1].toString());
				fbpbistolOA.setTool_stat(obj[2].toString());
				oaryList.add(fbpbistolOA);
			}
		}
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
		outTrx.setOary(oaryList);
		return outTrx;
	}

	public void addFnc(FbpbistolI inTrx,FbpbistolO outTrx) {
		FbpbistolIA iary = inTrx.getIary().get(0);
		Timestamp current_timestamp = Util.getCurrentTimestamp();
		String tool_id = iary.getTool_id();
		Bis_tool queryBisOpe = getDataByKeyProc(tool_id);
		if (queryBisOpe != null) {
			outTrx.setRtn_code(E_FBPBISTOL_ADD_TOOL_ALREADY_EXIST + "");
			outTrx.setRtn_mesg("Tool Already Exist");
			return;
		}
		/**
		 * Tool Basic Table
		 */
		Bis_tool bis_tool = new Bis_tool();
		bis_tool.setTool_id(tool_id);
		bis_tool.setTool_dsc(iary.getTool_dsc());
		bis_tool.setUnit_typ(iary.getUnit_typ());
		bis_tool.setRoot_tool_id(iary.getRoot_tool_id());
		bis_tool.setTool_cate(iary.getTool_cate());
		bis_tool.setBay_id(iary.getBay_id());
		bis_tool.setFloor_code(iary.getFloor_code());
		bis_tool.setFab_id_fk(iary.getFab_id_fk());
		bis_tool.setTool_ip(iary.getTool_ip());
		bis_tool.setTool_code(iary.getTool_code());
		bis_tool.setTool_trns_cate(iary.getTool_trns_cate());
		bis_tool.setEvt_timestamp(Util.getCurrentTimestamp());
		bis_tool.setFab_site_fk(iary.getFab_site_fk());
		bis_tool.setEvt_usr(iary.getEvt_usr());
		bisToolDao.save(bis_tool);
		
		/**
		 * Tool Group Table
		 */
		if("MAIN".equals(iary.getUnit_typ())){
			Bis_tool_grId bis_tool_grId = new Bis_tool_grId();
			Bis_tool_gr   bis_tool_gr = new Bis_tool_gr();
			bis_tool_grId.setTool_id_fk(iary.getTool_id());
			bis_tool_grId.setToolg_id(iary.getTool_group_id_fk());
			bis_tool_gr.setId(bis_tool_grId);
			bis_tool_gr.setUnq_seq_id(GUIDGenerator.javaGUID());
			bis_tool_gr.setValid_flg("Y");
			bis_tool_gr.setEvt_usr(iary.getEvt_usr());
			bis_tool_gr.setEvt_timestamp(Util.getCurrentTimestamp());
			bisToolGrDao.save(bis_tool_gr);
		}

		/**
		 * Tool State Table
		 */
		Ret_tool_st ret_tool_st = new Ret_tool_st();
		Integer k=0;
		ret_tool_st.setTool_id_fk(tool_id);
		ret_tool_st.setUnq_seq_id(GUIDGenerator.javaGUID());
		ret_tool_st.setTool_stat(TOOL_STAT_DOWN);
		ret_tool_st.setTool_sub_stat("3000");
		ret_tool_st.setTool_lock_flg(_NO);
		ret_tool_st.setTool_hold_flg(_NO);
		ret_tool_st.setTool_ctrl_mode(_SPACE);
		ret_tool_st.setTool_run_mode(iary.getTool_run_mode());
		ret_tool_st.setLd_rtd_flg(_NO);
		ret_tool_st.setUl_rtd_flg(_NO);
		ret_tool_st.setPv_tool_stat(_SPACE);
		ret_tool_st.setPv_tool_sub_stat(_SPACE);
		ret_tool_st.setClm_usr(inTrx.getEvt_usr());
		ret_tool_st.setPv_clm_timestamp(ret_tool_st.getClm_timestamp());
		ret_tool_st.setClm_timestamp(current_timestamp);
		ret_tool_st.setPv_clm_usr(_SPACE);
		ret_tool_st.setKeep_time(k);
		ret_tool_st.setTool_note(_SPACE);
    /*	ret_tool_st.setLst_xfr_timestamp(null);*/
		ret_tool_st.setLd_force_rtn_flg(_NO);
		ret_tool_st.setUl_force_rtn_flg(_NO);
		ret_tool_st.setLd_r_time(k);
		ret_tool_st.setUl_r_time(k);
		ret_tool_st.setEvt_usr(inTrx.getEvt_usr());
		ret_tool_st.setEvt_timestamp(current_timestamp);
		retToolStDao.save(ret_tool_st);
		
		/**
		 * Tool Port Table
		 */
		List<FbpbistolIB> iaryBList = inTrx.getIaryB();
		for(FbpbistolIB iaryB : iaryBList){
			Ret_tool_pt ret_tool_pt = new Ret_tool_pt();
			Ret_tool_ptId id = new Ret_tool_ptId();
			id.setTool_id_fk(tool_id);
			id.setPort_id(iaryB.getPort_id());
			ret_tool_pt.setId(id);
			ret_tool_pt.setPort_stat(_SPACE);
			ret_tool_pt.setPort_ng_flg(iaryB.getPort_ng_flg());
			ret_tool_pt.setPort_timestamp(current_timestamp);
			ret_tool_pt.setPort_typ(iaryB.getPort_typ());
			ret_tool_pt.setEvt_timestamp(current_timestamp);
			ret_tool_pt.setEvt_usr(inTrx.getEvt_usr());
			ret_tool_pt.setFrom_stk_id(iaryB.getFrom_stk_id());
			ret_tool_pt.setTo_stk_id(iaryB.getTo_stk_id());
			ret_tool_pt.setLst_xfr_timestamp(null);
			ret_tool_pt.setRtd_flg(_SPACE);
			ret_tool_pt.setXfr_id(iaryB.getXfr_id());
			ret_tool_pt.setXfr_node(iaryB.getXfr_node());
			ret_tool_pt.setPort_active_flg(iaryB.getPort_active_flg());
			
			retToolPtDao.save(ret_tool_pt);
		}
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);

	}

	public void updateFnc(FbpbistolI inTrx,FbpbistolO outTrx) {
		int i=0,k=0,j=0;
		FbpbistolIA iary = inTrx.getIary().get(0);
		List<FbpbistolIB> iaryBList = inTrx.getIaryB();
		Timestamp current_timestamp = Util.getCurrentTimestamp();
		String tool_id = iary.getTool_id();
		Bis_tool bis_tool = getDataByKeyProc(tool_id);
		if (bis_tool == null) {
			outTrx.setRtn_code(E_FBPBISTOL_ADD_TOOL_ALREADY_EXIST + "");
			outTrx.setRtn_code("Not found This tool["+tool_id+"]");
			return;
		}
		if (!Util.isSpaceCheck(iary.getTool_dsc())) {
			bis_tool.setTool_dsc(iary.getTool_dsc());
		}
		if (!Util.isSpaceCheck(iary.getUnit_typ())) {
			bis_tool.setUnit_typ(iary.getUnit_typ());
		}
		if (!Util.isSpaceCheck(iary.getRoot_tool_id())) {
			bis_tool.setRoot_tool_id(iary.getRoot_tool_id());
		}
		if (!Util.isSpaceCheck(iary.getTool_cate())) {
			bis_tool.setTool_cate(iary.getTool_cate());
		}
		if (!Util.isSpaceCheck(iary.getBay_id())) {
			bis_tool.setBay_id(iary.getBay_id());
		}
		if (!Util.isSpaceCheck(iary.getFloor_code())) {
			bis_tool.setFloor_code(iary.getFloor_code());
		}
		if (!Util.isSpaceCheck(iary.getTool_trns_cate())) {
			bis_tool.setTool_trns_cate(iary.getTool_trns_cate());
		}
		if (!Util.isSpaceCheck(iary.getTool_ip())) {
			bis_tool.setTool_ip(iary.getTool_ip());
		}
		if (!Util.isSpaceCheck(iary.getFab_id_fk())) {
			bis_tool.setFab_id_fk(iary.getFab_id_fk());
		}
		if (!Util.isSpaceCheck(iary.getTool_code())) {
			bis_tool.setTool_code(iary.getTool_code());
		}
		if (!Util.isSpaceCheck(iary.getFab_site_fk())){
			bis_tool.setFab_site_fk(iary.getFab_site_fk());
		}
		bis_tool.setEvt_usr(inTrx.getEvt_usr());
		bis_tool.setEvt_timestamp(current_timestamp);
		bisToolDao.update(bis_tool);
		
		//更新RET_TOOL_ST
		if(!Util.isSpaceCheck(iary.getTool_run_mode())){
			Ret_tool_st ret_tool_st = retToolStDao.get(tool_id);
			if(ret_tool_st != null){
				ret_tool_st.setTool_run_mode(iary.getTool_run_mode());	
				ret_tool_st.setEvt_usr(inTrx.getEvt_usr());
				ret_tool_st.setEvt_timestamp(current_timestamp);
				retToolStDao.update(ret_tool_st);
			}
		}

		/**
		 * update tool_group info
		 */
		if("MAIN".equals(iary.getUnit_typ())){
			//先删除原来的组，在更新现在的组
			String hqls = "FROM Bis_tool_gr where 1=1 ";
			if (iary.getTool_id() != null) {
				hqls = hqls + " and tool_id_fk='" + iary.getTool_id() + "'";
			}
			List<Bis_tool_gr> bisToolGr = bisToolGrDao.find(hqls);
			if(bisToolGr.size()>0){
				bisToolGrDao.deleteAll(bisToolGr);
			}
			Bis_tool_grId bis_tool_grId = new Bis_tool_grId();
			Bis_tool_gr   bis_tool_gr = new Bis_tool_gr();
			bis_tool_grId.setTool_id_fk(iary.getTool_id());
			bis_tool_grId.setToolg_id(iary.getTool_group_id_fk());
			bis_tool_gr.setId(bis_tool_grId);
			bis_tool_gr.setUnq_seq_id(GUIDGenerator.javaGUID());
			bis_tool_gr.setValid_flg("Y");
			bis_tool_gr.setEvt_usr(inTrx.getEvt_usr());
			bis_tool_gr.setEvt_timestamp(Util.getCurrentTimestamp());
			bisToolGrDao.save(bis_tool_gr);
		}

		/**
		 * update port info
		 */
		String hql = "FROM Ret_tool_pt where tool_id_fk='" + tool_id+"'";
		List<Ret_tool_pt> bisToolPtList = retToolPtDao.find(hql);
		/**
		 * delete no need port info
		 */
		if(bisToolPtList.size()>0){
			for(j=0; j<bisToolPtList.size(); j++){
				Ret_tool_pt ret_tool_pt = bisToolPtList.get(j);
				for(k=0; k<iaryBList.size(); k++){
					FbpbistolIB iaryB = inTrx.getIaryB().get(k);
					if( ret_tool_pt.getId().getTool_id_fk().trim().equals(tool_id.trim())
							&&ret_tool_pt.getId().getPort_id().trim().equals(iaryB.getPort_id().trim()) ){
						break;
					}
				}
				if(k>=iaryBList.size()){
					retToolPtDao.delete(ret_tool_pt);
				}
			}
		}
		/**
		 * add&update port info
		 */
		for(FbpbistolIB iaryB : iaryBList){
			Ret_tool_ptId id = new Ret_tool_ptId();
			id.setTool_id_fk(tool_id);
			id.setPort_id(iaryB.getPort_id());
			Ret_tool_pt pt = retToolPtDao.get(id);
			if(pt == null){
				Ret_tool_pt ret_tool_pt = new Ret_tool_pt();
				ret_tool_pt.setId(id);
				ret_tool_pt.setPort_stat(_SPACE);
				ret_tool_pt.setPort_ng_flg(iaryB.getPort_ng_flg());
				ret_tool_pt.setPort_timestamp(current_timestamp);
				ret_tool_pt.setPort_typ(iaryB.getPort_typ());
				ret_tool_pt.setEvt_timestamp(current_timestamp);
				ret_tool_pt.setEvt_usr(inTrx.getEvt_usr());
				ret_tool_pt.setFrom_stk_id(iaryB.getFrom_stk_id());
				ret_tool_pt.setTo_stk_id(iaryB.getTo_stk_id());
				ret_tool_pt.setLst_xfr_timestamp(null);
				ret_tool_pt.setRtd_flg(_SPACE);
				ret_tool_pt.setXfr_id(iaryB.getXfr_id());
				ret_tool_pt.setXfr_node(iaryB.getXfr_node());
				ret_tool_pt.setPort_active_flg(iaryB.getPort_active_flg());
				ret_tool_pt.setEvt_usr(inTrx.getEvt_usr());
				ret_tool_pt.setEvt_timestamp(current_timestamp);
				retToolPtDao.save(ret_tool_pt);
			}else{
				pt.setPort_typ(iaryB.getPort_typ());
				pt.setPort_active_flg(iaryB.getPort_active_flg());
				pt.setFrom_stk_id(iaryB.getFrom_stk_id());
				pt.setTo_stk_id(iaryB.getTo_stk_id());
				pt.setPort_ng_flg(iaryB.getPort_ng_flg());
				pt.setXfr_id(iaryB.getXfr_id());
				pt.setXfr_node(iaryB.getXfr_node());
				pt.setEvt_usr(inTrx.getEvt_usr());
				pt.setEvt_timestamp(current_timestamp);
				retToolPtDao.update(pt);
			}
		}
		
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
		
		

	}

	public void deleteFnc(FbpbistolI inTrx,FbpbistolO outTrx) {
		FbpbistolIA iary = inTrx.getIary().get(0);
		String tool_id = iary.getTool_id();
		Bis_tool bis_tool = getDataByKeyProc(tool_id);
		if (bis_tool == null) {
			outTrx.setRtn_code(E_FBPBISTOL_NOT_FOUND_RECORD + "");
			outTrx.setRtn_code("not found tool_id[" + tool_id + "]");
			return;
		}
		bisToolDao.delete(bis_tool);
		//删除群组信息，
		String hqls = "FROM Bis_tool_gr where 1=1 ";
		if (iary.getTool_id() != null) {
			hqls = hqls + " and tool_id_fk='" + iary.getTool_id() + "'";
		}
		List<Bis_tool_gr> bisToolGr = bisToolGrDao.find(hqls);
		if(bisToolGr.size()>0){
			bisToolGrDao.delete(bisToolGr.get(0));
		}
		/**
		 * delete tool stat info
		 */
		Ret_tool_st ret_tool_st = retToolStDao.get(tool_id);
		if(ret_tool_st != null){
			retToolStDao.delete(ret_tool_st);
		}
		/**
		 * delete port info
		 */
		String hql_port = "FROM Ret_tool_pt where tool_id_fk ='"+ iary.getTool_id() + "'";
		List<Ret_tool_pt> retToolPtList = retToolPtDao.find(hql_port);
		for(Ret_tool_pt ret_tool_pt : retToolPtList){
			retToolPtDao.delete(ret_tool_pt);
		}
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
	}

	public void queryByCondition(FbpbistolI inTrx,FbpbistolO outTrx) {
		FbpbistolIA iary = inTrx.getIary().get(0);
		/***
		 * 支持 按tool_id,unit_typ,tool_cate查询 支持 按ope_id查询,ope_id
		 * ==>tool_group==>tool_id
		 ***/
		String tool_id = iary.getTool_id();
		String hql = "FROM Bis_tool where 1=1 ";
		if (tool_id != null && !tool_id.equals(_SPACE)) {
			if (tool_id.indexOf('*') == -1) {
				hql = hql + " and tool_id='" + tool_id + "'";
			} else {
				hql = hql + " and tool_id like '" + tool_id.replace('*', '%') + "'";
			}
		}
		if (iary.getUnit_typ() != null && !iary.getUnit_typ().equals(_SPACE)) {
			hql = hql + " and unit_typ='" + iary.getUnit_typ() + "'";
		}
		if (iary.getTool_cate() != null && !iary.getTool_cate().equals(_SPACE)) {
			hql = hql + " and tool_cate='" + iary.getTool_cate() + "'";
		}
		if(iary.getFab_site_fk()!= null && !iary.getFab_site_fk().equals(_SPACE) ){
			hql = hql +"and fab_site_fk = '" +iary.getFab_site_fk()+"'";
		}
		if(iary.getFab_id_fk()!= null && !iary.getFab_id_fk().equals(_SPACE)
				&& !"*".equals(iary.getFab_id_fk())){
			hql = hql +"and fab_id_fk  = '" +iary.getFab_id_fk()+"'";
		}
		if (iary.getBay_id() != null && !iary.getBay_id().equals(_SPACE)
				&& !"*".equals(iary.getBay_id())) {
			hql = hql + " and bay_id='" + iary.getBay_id() + "'";
		}
		if (iary.getRoot_tool_id() != null && !iary.getRoot_tool_id().equals(_SPACE)) {
			hql = hql + "and root_tool_id = '" +iary.getRoot_tool_id()+"'";
		}
		if(!StringUtils.isEmpty(iary.getOpe_id_fk()) && !StringUtils.isEmpty(iary.getOpe_ver())
				&& !"*".equals(iary.getOpe_id_fk())){
			Bis_opeId opeId = new Bis_opeId();
			opeId.setOpe_id(iary.getOpe_id_fk());
			opeId.setOpe_ver(iary.getOpe_ver());
			Bis_ope bis_ope = bisOpeDao.get(opeId);
			if(bis_ope==null){
				outTrx.setRtn_code(E_BIS_OPE + E_READ_NOT_FOUND +"");
				outTrx.setRtn_mesg("NOT FOUND operation["+iary.getOpe_id_fk()+"][" + iary.getOpe_ver() + "]");
				return ;
			}
			hql = hql + " and tool_id in ( select id.tool_id_fk from Bis_tool_gr where " +
					"id.toolg_id ='"+ bis_ope.getToolg_id_fk() + "')";
			
		}else if(iary.getTool_group_id_fk() != null && !iary.getTool_group_id_fk().equals(_SPACE)){
			hql = hql + " and tool_id in ( select id.tool_id_fk from Bis_tool_gr where " +
					"id.toolg_id ='"+ iary.getTool_group_id_fk() + "')";
		}
		
		/**
		 * 去掉stocker
		 */
		hql = hql + " and tool_cate <> 'STOC'";
		List<Bis_tool> bisToolList = bisToolDao.find(hql);
		List<FbpbistolOA> oaryList = new ArrayList<FbpbistolOA>();
		List<Bis_tool> oaryCList = new ArrayList<Bis_tool>();
		for (Bis_tool bis_tool : bisToolList) {
			FbpbistolOA oary = new FbpbistolOA();
			oary.setTool_id(bis_tool.getTool_id());
			oary.setTool_dsc(bis_tool.getTool_dsc());
			oary.setUnit_typ(bis_tool.getUnit_typ());
			oary.setRoot_tool_id(bis_tool.getRoot_tool_id());
			oary.setTool_cate(bis_tool.getTool_cate());
			oary.setBay_id(bis_tool.getBay_id());
			oary.setFloor_code(bis_tool.getFloor_code());
			oary.setTool_trns_cate(bis_tool.getTool_trns_cate());
			oary.setTool_ip(bis_tool.getTool_ip());
			oary.setFab_id_fk(bis_tool.getFab_id_fk());
			oary.setTool_code(bis_tool.getTool_code());
			oaryList.add(oary);
			if(Util.isSpaceCheck(bis_tool.getTool_code())){
				oaryCList.add(bis_tool);
			}
		}
		
		
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
		outTrx.setOary(oaryList);
		outTrx.setTbl_cnt(oaryList.size());
		outTrx.setOaryC(oaryCList);
	}

	public void getRootTool(FbpbistolI inTrx,FbpbistolO outTrx){
		String hql = "From Bis_tool where 1 = 1";
		List<Bis_tool>  bis_tools= bisToolDao.find(hql);
		Set<String> rootToolList =  new HashSet<String>();
		for(int i = 0; i < bis_tools.size(); i++){
			String rootToolId = bis_tools.get(i).getRoot_tool_id();
			if(!StringUtils.isEmpty(rootToolId)){
				rootToolList.add(rootToolId);
			}
		}

		List<FbpbistolOA> oaryList = new ArrayList<FbpbistolOA>();
		Iterator<String> it = rootToolList.iterator();
		while (it.hasNext()) {
			FbpbistolOA oary = new FbpbistolOA();
			String str = it.next();
			oary.setRoot_tool_id(str);
			oaryList.add(oary);
		}
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
		outTrx.setOary(oaryList);
		outTrx.setTbl_cnt(oaryList.size());
	}

	public void getRootToolByToolId(FbpbistolI inTrx,FbpbistolO outTrx) {
		FbpbistolIA iary = inTrx.getIary().get(0);
		String tool_id = iary.getTool_id();
		Bis_tool bis_tool = bisToolDao.get(tool_id);
		Bis_tool bisTool = bisToolDao.get(bis_tool.getRoot_tool_id());
		List<FbpbistolOA> oaryList = new ArrayList<FbpbistolOA>();
		FbpbistolOA oary = new FbpbistolOA();
		oary.setTool_id(bisTool.getTool_id());
		oary.setTool_dsc(bisTool.getTool_dsc());
		oary.setUnit_typ(bisTool.getUnit_typ());
		oary.setRoot_tool_id(bisTool.getRoot_tool_id());
		oary.setTool_cate(bisTool.getTool_cate());
		oary.setBay_id(bisTool.getBay_id());
		oary.setFloor_code(bisTool.getFloor_code());
		oary.setTool_trns_cate(bisTool.getTool_trns_cate());
		oary.setTool_ip(bisTool.getTool_ip());
		oary.setFab_id_fk(bisTool.getFab_id_fk());
		oaryList.add(oary);
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
		outTrx.setOary(oaryList);
		outTrx.setTbl_cnt(oaryList.size());
		return;
	}



	public void listAllFnc(FbpbistolO outTrx) {
		List<FbpbistolOA> oaryList = new ArrayList<FbpbistolOA>();
		String hql = "FROM Bis_tool where 1=1 ";
		List<Bis_tool> bisToolList = bisToolDao.find(hql);
		for (Bis_tool bis_tool : bisToolList) {
			FbpbistolOA oary = new FbpbistolOA();
			oary.setTool_id(bis_tool.getTool_id());
			oary.setTool_dsc(bis_tool.getTool_dsc());
			oary.setBay_id(bis_tool.getBay_id());
			oaryList.add(oary);
		}
		outTrx.setOary(oaryList);
		outTrx.setTbl_cnt(oaryList.size());
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);

	}
	public void queryToolByFacyory(FbpbistolI inTrx,FbpbistolO outTrx) {
		FbpbistolIA iary = inTrx.getIary().get(0);
        String fabSiteFk = iary.getFab_site_fk();
        String fabIdFk   = iary.getFab_id_fk();
        String bayId     = iary.getBay_id();
        String opeIdFk   = iary.getOpe_id_fk();


		List<FbpbistolOA> oaryList = new ArrayList<FbpbistolOA>();
        //站点绑定机台群组，群组限定设备
		List<Bis_ope> bis_opes = new ArrayList<>();
		List<Bis_tool_gr>   bis_tool_grs = new ArrayList<>();
        if(opeIdFk != null && !opeIdFk.equals(_SPACE)){
        	String hql = "FROM Bis_ope where ope_id = '" +opeIdFk+"'";
			bis_opes = bisOpeDao.find(hql);
			if(bis_opes.size()>0){
				Bis_ope  bis_ope = bis_opes.get(0);
				String sql = "SELECT * from BIS_TOOL t LEFT JOIN BIS_TOOL_GR g on t.tool_id=g.tool_id_fk where 1=1";
				if(bis_ope.getToolg_id_fk() != null && !bis_ope.getToolg_id_fk().equals(_SPACE)){
                       sql = sql +"and g.toolg_id = '" +bis_ope.getToolg_id_fk()+"'";
				}
				if(fabSiteFk!= null && !fabSiteFk.equals(_SPACE)){
					   sql = sql +"and t.fab_site_fk = '" +fabSiteFk+"'";
				}
				if(fabIdFk!= null && !fabIdFk.equals(_SPACE)){
					   sql = sql +"and t.fab_id_fk = '" +fabIdFk+"'";
				}
				if(bayId!= null && !bayId.equals(_SPACE)){
					   sql = sql +"and t.bay_id = '" +bayId+"'";
				}
				Session session = bisToolDao.getCrSession();
				List<Bis_tool> bisToolList = session.createSQLQuery(sql).addEntity(Bis_tool.class).list();
				for(Bis_tool bis_tool : bisToolList){
					FbpbistolOA oary = new FbpbistolOA();
					oary.setTool_id(bis_tool.getTool_id());
					oary.setTool_dsc(bis_tool.getTool_dsc());
					oary.setTool_group_id_fk( bis_ope.getToolg_id_fk());
					oary.setFab_site_fk(bis_tool.getFab_site_fk());
					oary.setFab_id_fk(bis_tool.getFab_id_fk());
					oaryList.add(oary);
				}
			}
		}else {
			String sql = "SELECT * from BIS_TOOL t LEFT JOIN BIS_TOOL_GR g on t.tool_id=g.tool_id_fk where 1=1";
			if(fabSiteFk!= null && !fabSiteFk.equals(_SPACE)){
				sql = sql +" and t.fab_site_fk = '" +fabSiteFk+"'";
			}
			if(fabIdFk!= null && !fabIdFk.equals(_SPACE)){
				sql = sql +" and t.fab_id_fk  = '" +fabIdFk+"'";
			}
			if(bayId!= null && !bayId.equals(_SPACE)){
				sql = sql +" and t.bay_id = '" +bayId+"'";
			}
			Session session = bisToolDao.getCrSession();
			List<Bis_tool> bisToolList = session.createSQLQuery(sql).addEntity(Bis_tool.class).list();
			for(Bis_tool bis_tool : bisToolList){
				FbpbistolOA oary = new FbpbistolOA();
				oary.setTool_id(bis_tool.getTool_id());
				oary.setTool_dsc(bis_tool.getTool_dsc());
				oary.setFab_site_fk(bis_tool.getFab_site_fk());
				oary.setFab_id_fk(bis_tool.getFab_id_fk());
				oaryList.add(oary);
			}
		}
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
		outTrx.setOary(oaryList);
		outTrx.setTbl_cnt(oaryList.size());
	}
	public Bis_tool getDataByKeyProc(String tool_id) {
		Bis_tool bis_tool = bisToolDao.get(tool_id);
		return bis_tool;
	}

	public void errActionFnc(FbpbistolO outTrx) {
		outTrx.setRtn_code("0000009");
		outTrx.setRtn_mesg("Invalid Action_flg");
	}
	private void getToolByProc(FbpbistolI inTrx, FbpbistolO outTrx) {

		List<FbpbistolOA> oaryAList = new ArrayList<FbpbistolOA>();
		FbpbistolIA iary = inTrx.getIary().get(0);
		String procId   = iary.getProc_id();
		String toolg_id = iary.getTool_group_id_fk();
		String ope_id   = iary.getOpe_id_fk();
		/*String sql = "SELECT * from BIS_TOOL_GR g LEFT JOIN BIS_OPE o on o.toolg_id_fk = g.toolg_id where 1=1";
		if(procId!= null && !procId.equals(_SPACE)){
			sql = sql +" and o.proc_id = '" +procId+"'";
		}
		if(toolg_id!= null && !toolg_id.equals(_SPACE)){
			sql = sql +" and g.toolg_id = '" +toolg_id+"'";
		}
		Session session = bisToolGrDao.getCrSession();
		List<Bis_tool_gr> bis_tool_grList = session.createSQLQuery(sql).addEntity(Bis_tool_gr.class).list();
		for(Bis_tool_gr bis_tool_gr : bis_tool_grList){
			FbpbistolOA oary = new FbpbistolOA();
			Bis_tool bis_tool = bisToolDao.get(bis_tool_gr.getId().getTool_id_fk());
			oary.setTool_id(bis_tool.getTool_id());
			oary.setFab_id_fk(bis_tool.getFab_id_fk());
			oary.setTool_group_id_fk(bis_tool.getRoot_tool_id());
			oary.setBay_id(bis_tool.getBay_id());
			oaryAList.add(oary);
		}*/
		String hql = "FROM Bis_ope where 1=1";
		if(procId!= null && !procId.equals(_SPACE)){
			hql =  hql +" and proc_id = '" +procId+"'";
		}
		if(toolg_id!= null && !toolg_id.equals(_SPACE)){
			hql =  hql +" and toolg_id_fk = '" +toolg_id+"'";
		}
		if(ope_id!= null && !ope_id.equals(_SPACE)){
			hql =  hql +" and ope_id = '" +ope_id+"'";
		}
        List<Bis_ope> opeList = bisOpeDao.find(hql);
			for (Bis_ope bis_ope : opeList) {
				String hqlM = "FROM Bis_tool_gr where toolg_id ='" + bis_ope.getToolg_id_fk() + "'";
				List<Bis_tool_gr> bisToolGrs = bisToolGrDao.find(hqlM);
				for (Bis_tool_gr bis_tool_gr : bisToolGrs) {
					FbpbistolOA oary = new FbpbistolOA();
					Bis_tool bis_tool = bisToolDao.get(bis_tool_gr.getId().getTool_id_fk());
					oary.setTool_id(bis_tool.getTool_id());
					oary.setFab_id_fk(bis_tool.getFab_id_fk());
					oary.setTool_group_id_fk(bis_tool.getRoot_tool_id());
					oary.setBay_id(bis_tool.getBay_id());
					oary.setTool_dsc(bis_tool.getTool_dsc());
					oaryAList.add(oary);
				}
			}
		outTrx.setOary(oaryAList);
		outTrx.setTbl_cnt(oaryAList.size());
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
	}

	private void querytoolStatus(FbpbistolI inTrx, FbpbistolO outTrx) {
		FbpbistolIA iary = inTrx.getIary().get(0);
		String tool_id = iary.getTool_id();
		Bis_tool bis_tool = getDataByKeyProc(tool_id);
		if (bis_tool == null) {
			outTrx.setRtn_code(E_FBPBISTOL_NOT_FOUND_RECORD + "");
			outTrx.setRtn_code("not found tool_id[" + tool_id + "]");
			return;
		}
		//获取上次保养时间
		String hql_pv_tool_pm="From Ret_tool_pm where 1=1 and tool_id_fk='" + iary.getTool_id()
				+ "' and pm_stat='COMP' order by from_date desc";
		List<Ret_tool_pm> pv_tool_pm_list = retToolPmDao.find(hql_pv_tool_pm);
		if(pv_tool_pm_list.size()>0){
			outTrx.setPv_pm_date(pv_tool_pm_list.get(0).getFrom_date().toString().substring(0, 10));
		}else{
			outTrx.setPv_pm_date(_SPACE);
		}
		//获取下次保养时间
		String hql_nx_tool_pm="From Ret_tool_pm where 1=1 and tool_id_fk='" + iary.getTool_id()
				+ "' and pm_stat<>'COMP' order by from_date asc";
		List<Ret_tool_pm> tool_nx_pm_list = retToolPmDao.find(hql_nx_tool_pm);
		if(tool_nx_pm_list.size()>0){
			outTrx.setNx_pm_date(tool_nx_pm_list.get(0).getFrom_date().toString().substring(0, 10));
		}else{
			outTrx.setNx_pm_date(_SPACE);
		}
		Ret_tool_st ret_tool_st = retToolStDao.get(tool_id);
		if (ret_tool_st == null) {
			outTrx.setRtn_code(E_FBPBISTOL_NOT_FOUND_RECORD + "");
			outTrx.setRtn_code("设备[" + tool_id +"]状态信息不存在");
			return;
		}
		outTrx.setTool_stat(ret_tool_st.getTool_stat());
		outTrx.setEvt_timestamp(ret_tool_st.getEvt_timestamp().toString().substring(0, 10));
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
	}
}
